class StorageManager {
  private storage: Storage

  constructor(type: 'localStorage' | 'sessionStorage') {
    this.storage = type === 'localStorage' ? window.localStorage : window.sessionStorage
  }

  set(key: string, val: any): void {
    this.storage.setItem(key, JSON.stringify(val))
  }

  get(key: string): any {
    const json = this.storage.getItem(key)
    if (json !== null) {
      try {
        return JSON.parse(json)
      } catch (error) {
        console.error('无法解析JSON:', error)
        return json // 或者返回一个包含错误的对象，取决于您的业务需求
      }
    }
    return null
  }

  remove(key: string): void {
    this.storage.removeItem(key)
  }

  clear(): void {
    this.storage.clear()
  }
}

export const localStore = new StorageManager('localStorage')
export const sessionStore = new StorageManager('sessionStorage')
